<template>
  <div class="response-display-container">
    <!-- 回答头部信息 -->
    <div class="response-header">
      <div class="header-left">
        <el-avatar
          :size="32"
          icon="ChatRound"
          class="system-avatar"
          :style="{ backgroundColor: modelColor }"
        >
          <span class="avatar-text">AI</span>
        </el-avatar>
        <div class="header-info">
          <div class="model-info">
            <span class="model-name">{{ modelName }}</span>
            <el-tag
              v-if="showModelType"
              :type="getModelTagType(modelType)"
              size="small"
              effect="plain"
            >
              {{ modelType }}
            </el-tag>
          </div>
          <div v-if="showResponseTime" class="response-time">
            {{ formatResponseTime }}
          </div>
        </div>
      </div>

      <div class="header-actions">
        <el-tooltip content="复制全部内容" placement="top">
          <el-button
            type="primary"
            text
            circle
            @click="copyAllContent"
            size="small"
          >
            <el-icon><CopyDocument /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 回答内容 -->
    <div
      class="response-content"
      :class="{ 'is-collapsed': isCollapsed && shouldCollapse }"
    >
      <!-- Markdown渲染区域 -->
      <div class="markdown-content" ref="markdownRef"></div>

      <!-- 折叠按钮 -->
      <div
        v-if="shouldCollapse"
        class="collapse-actions"
      >
        <el-button
          type="primary"
          text
          @click="toggleCollapse"
        >
          <el-icon v-if="isCollapsed"><ArrowDown /></el-icon>
          <el-icon v-else><ArrowUp /></el-icon>
          {{ isCollapsed ? '展开全部' : '收起内容' }}
        </el-button>
      </div>
    </div>

    <!-- Token信息 -->
    <div v-if="showTokenInfo && (queryTokens || responseTokens)" class="token-info">
      <el-tag
        type="info"
        size="small"
        effect="plain"
      >
        <el-icon><ChatLineSquare /></el-icon>
        询问：{{ formatTokens(queryTokens) }}
      </el-tag>
      <el-tag
        type="info"
        size="small"
        effect="plain"
      >
        <el-icon><ChatLineRound /></el-icon>
        回答：{{ formatTokens(responseTokens) }}
      </el-tag>
      <el-tag
        :type="getTokenColorType(totalTokens)"
        size="small"
        effect="plain"
      >
        <el-icon><ChatDotRound /></el-icon>
        总计：{{ formatTokens(totalTokens) }}
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  CopyDocument,
  ChatLineSquare,
  ChatLineRound,
  ChatDotRound,
  ArrowDown,
  ArrowUp
} from '@element-plus/icons-vue'
import { formatTimestamp, formatTokens, getTokenColorType } from '@/utils/queryDataProcessor'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

// 定义属性
const props = defineProps({
  // 回答内容
  content: {
    type: String,
    required: true
  },

  // 模型信息
  modelName: {
    type: String,
    default: 'AI助手'
  },
  modelType: {
    type: String,
    default: ''
  },

  // 时间信息
  responseTime: {
    type: [String, Number, Date],
    default: null
  },

  // Token信息
  queryTokens: {
    type: Number,
    default: 0
  },
  responseTokens: {
    type: Number,
    default: 0
  },

  // 界面配置
  showResponseTime: {
    type: Boolean,
    default: true
  },
  showModelType: {
    type: Boolean,
    default: true
  },
  showTokenInfo: {
    type: Boolean,
    default: true
  },
  collapsible: {
    type: Boolean,
    default: true
  },
  maxHeight: {
    type: Number,
    default: 500
  }
})

// 定义事件
const emit = defineEmits(['copied'])

// 状态
const isCollapsed = ref(true)
const contentHeight = ref(0)
const markdownRef = ref(null)

// 计算属性
const formatResponseTime = computed(() => {
  if (!props.responseTime) return ''
  return formatTimestamp(props.responseTime)
})

const totalTokens = computed(() => {
  return props.queryTokens + props.responseTokens
})

const shouldCollapse = computed(() => {
  return props.collapsible && contentHeight.value > props.maxHeight
})

const modelColor = computed(() => {
  const modelTypeMap = {
    'gpt-3.5': '#19C37D',
    'gpt-3.5-turbo': '#19C37D',
    'gpt-4': '#AB68FF',
    'gpt-4-turbo': '#AB68FF',
    'claude-2': '#565869',
    'claude-3': '#565869'
  }

  if (props.modelType && modelTypeMap[props.modelType]) {
    return modelTypeMap[props.modelType]
  }

  // 根据模型名称判断
  const modelName = props.modelName.toLowerCase()
  if (modelName.includes('gpt-3')) return '#19C37D'
  if (modelName.includes('gpt-4')) return '#AB68FF'
  if (modelName.includes('claude')) return '#565869'

  // 默认颜色
  return '#409EFF'
})

// 方法
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

const copyAllContent = () => {
  try {
    navigator.clipboard.writeText(props.content)
    ElMessage.success('已复制到剪贴板')
    emit('copied', props.content)
  } catch (err) {
    console.error('复制失败', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

const getModelTagType = (modelType) => {
  if (!modelType) return ''

  const typeMap = {
    'gpt-3.5': 'success',
    'gpt-3.5-turbo': 'success',
    'gpt-4': 'primary',
    'gpt-4-turbo': 'primary',
    'claude-2': 'warning',
    'claude-3': 'warning'
  }

  return typeMap[modelType] || ''
}

const setupCodeCopyButtons = () => {
  if (!markdownRef.value) return

  const codeBlocks = markdownRef.value.querySelectorAll('pre code')

  codeBlocks.forEach((codeBlock, index) => {
    // 创建代码块容器
    const container = document.createElement('div')
    container.className = 'code-block-container'

    // 添加代码语言标签
    const langClass = Array.from(codeBlock.classList).find(cl => cl.startsWith('language-'))
    if (langClass) {
      const language = langClass.replace('language-', '')
      const langTag = document.createElement('div')
      langTag.className = 'code-language'
      langTag.innerText = language
      container.appendChild(langTag)
    }

    // 创建复制按钮
    const copyButton = document.createElement('button')
    copyButton.className = 'code-copy-button'
    copyButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="M8 3v2h12v12h2V3H8Z"></path><path fill="currentColor" d="M4 9a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V9Zm2 0v10h10V9H6Z"></path></svg>'
    copyButton.setAttribute('data-code-index', index)
    copyButton.addEventListener('click', (e) => {
      e.preventDefault()
      e.stopPropagation()

      const codeText = codeBlock.textContent
      navigator.clipboard.writeText(codeText)
        .then(() => {
          ElMessage.success('代码已复制')
          copyButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="m10.586 13.414-2.758-2.758 1.414-1.414 1.344 1.344 4.172-4.172 1.414 1.414-5.586 5.586Z"></path><path fill="currentColor" d="M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0 16a7 7 0 1 1 0-14 7 7 0 0 1 0 14Z"></path></svg>'
          setTimeout(() => {
            copyButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="M8 3v2h12v12h2V3H8Z"></path><path fill="currentColor" d="M4 9a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V9Zm2 0v10h10V9H6Z"></path></svg>'
          }, 2000)
        })
        .catch(err => {
          console.error('复制失败', err)
          ElMessage.error('复制失败')
        })
    })

    // 将代码块包裹到容器中
    const parent = codeBlock.parentNode
    container.appendChild(copyButton)
    parent.parentNode.insertBefore(container, parent)
    container.appendChild(parent)
  })
}

const renderMarkdown = () => {
  if (!markdownRef.value || !props.content) return

  // 配置marked
  marked.setOptions({
    highlight: (code, lang) => {
      const language = hljs.getLanguage(lang) ? lang : 'plaintext'
      return hljs.highlight(code, { language }).value
    },
    breaks: true,
    gfm: true
  })

  // 渲染Markdown
  markdownRef.value.innerHTML = marked(props.content)

  // 添加代码复制按钮
  setupCodeCopyButtons()

  // 计算内容高度
  contentHeight.value = markdownRef.value.scrollHeight
}

// 生命周期钩子
onMounted(() => {
  renderMarkdown()
})

// 侦听器
watch(() => props.content, () => {
  renderMarkdown()
})
</script>

<style scoped>
.response-display-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
  overflow: hidden;
}

.response-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--el-fill-color-light);
  border-bottom: 1px solid var(--el-border-color-light);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.system-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.avatar-text {
  font-size: 14px;
  font-weight: bold;
}

.header-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.model-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.model-name {
  font-weight: bold;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.response-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.header-actions {
  display: flex;
  gap: 8px;
}

.response-content {
  padding: 16px;
  overflow: hidden;
  transition: max-height 0.3s;
}

.response-content.is-collapsed {
  max-height: v-bind('props.maxHeight + "px"');
  overflow: hidden;
  position: relative;
}

.markdown-content {
  line-height: 1.6;
}

.collapse-actions {
  display: flex;
  justify-content: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px dashed var(--el-border-color-light);
}

.token-info {
  padding: 8px 16px;
  display: flex;
  gap: 12px;
  border-top: 1px solid var(--el-border-color-light);
  background-color: var(--el-fill-color-light);
}

/* Markdown样式 */
:deep(.markdown-content) {
  /* 标题样式 */
  h1, h2, h3, h4, h5, h6 {
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: bold;
    line-height: 1.25;
  }

  h1 {
    font-size: 1.7em;
    padding-bottom: 0.3em;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  h2 {
    font-size: 1.4em;
    padding-bottom: 0.3em;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  h3 {
    font-size: 1.25em;
  }

  h4 {
    font-size: 1.1em;
  }

  /* 段落样式 */
  p {
    margin-bottom: 16px;
  }

  /* 列表样式 */
  ul, ol {
    padding-left: 2em;
    margin-bottom: 16px;
  }

  li {
    margin-bottom: 4px;
  }

  /* 表格样式 */
  table {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 16px;
    overflow: auto;
  }

  th, td {
    padding: 8px 13px;
    border: 1px solid var(--el-border-color);
  }

  thead tr {
    background-color: var(--el-fill-color-light);
    border-top: 1px solid var(--el-border-color);
    font-weight: bold;
  }

  tbody tr:nth-child(2n) {
    background-color: var(--el-fill-color-lighter);
  }

  /* 代码样式 */
  code {
    font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
    padding: 0.2em 0.4em;
    margin: 0;
    font-size: 85%;
    background-color: rgba(175, 184, 193, 0.2);
    border-radius: 3px;
  }

  pre {
    padding: 16px;
    overflow: auto;
    font-size: 85%;
    line-height: 1.45;
    background-color: var(--el-fill-color-darker);
    border-radius: 6px;
    word-break: normal;
    word-wrap: normal;
    margin-bottom: 16px;
  }

  pre code {
    padding: 0;
    margin: 0;
    background-color: transparent;
    border: 0;
    word-break: normal;
    white-space: pre;
  }

  /* 引用样式 */
  blockquote {
    margin: 0 0 16px;
    padding: 0 1em;
    color: var(--el-text-color-secondary);
    border-left: 0.25em solid var(--el-border-color);
  }

  /* 水平线样式 */
  hr {
    height: 0.25em;
    padding: 0;
    margin: 24px 0;
    background-color: var(--el-border-color-light);
    border: 0;
  }

  /* 链接样式 */
  a {
    color: var(--el-color-primary);
    text-decoration: none;
  }

  a:hover {
    text-decoration: underline;
  }

  /* 图片样式 */
  img {
    max-width: 100%;
    box-sizing: content-box;
    border-radius: 4px;
  }
}

/* 代码块容器样式 */
:deep(.code-block-container) {
  position: relative;
  margin-bottom: 16px;
}

:deep(.code-language) {
  position: absolute;
  top: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.3);
  color: #fff;
  padding: 2px 8px;
  font-size: 12px;
  border-bottom-left-radius: 4px;
}

:deep(.code-copy-button) {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px;
  cursor: pointer;
  outline: none;
  transition: background-color 0.3s;
  z-index: 1;
}

:deep(.code-copy-button:hover) {
  background-color: rgba(255, 255, 255, 0.2);
}

@media (max-width: 768px) {
  .response-header {
    padding: 8px 12px;
  }

  .response-content {
    padding: 12px;
  }

  .token-info {
    flex-wrap: wrap;
    padding: 8px 12px;
  }
}
</style>
